/**
 * 对chrome.task 的集中转换为promise 解决方案
 * @author aker
 * @date 2019-8-20
 */

import { customChrome } from './Utils'

export default class ChromeCtl {
  public static chromeGetInfo():Promise<any> {
    return new Promise((resolve, reject) => {
      customChrome.task.getInfo((info) => {
        if (!info) {
          return reject('没有找到设备信息')
        }
        resolve(info)
      })
    })
  }
  public static chromeSaveSnapshot(params:any):Promise<{path:string, size:number, success:boolean, error:number, thumbnailPath:string}> {
    return new Promise((resolve) => {
      customChrome.task.snapshot(params, (result) => {
        resolve(result)
      })
    })
  }
  public static chromeTabsCreate(params:any={url: ""}):Promise<any> {
    return new Promise((resolve) => {
      chrome.tabs.create(params, res => {
        resolve(res)
      })
    })
  }
  public static chromeTabsQuery(query:any={active: true, currentWindow: true}):Promise<chrome.tabs.Tab[]> {
    return new Promise((resolve) => {
      chrome.tabs.query(query, tabs => {
        resolve(tabs)
      })
    })
  }
  public static resolveCookies(cookies:chrome.cookies.Cookie[]) {
    if (!cookies) return ""
    const cookiesArray:string[] = []
    for (const cookieEntity of cookies) {
      const cookieTmp = cookieEntity.name + '=' + cookieEntity.value + ';'
      cookiesArray.push(cookieTmp)
    }
    return cookiesArray.join('') // 得到cookie
  }
  static chromeDownloadsDownloadPromise(options:any):Promise<number> {
    return new Promise((resolve) => {
      chrome.downloads.download(options, (downloadId) => {
        resolve(downloadId)
      })
    })
  }
  public static chrometabsExecuteScript(tabId:number, type:"code"|"file", params):Promise<any[]> {
    return new Promise((resolve) => {
      let data = type === "code" ? { code: params } : { file: params }
      chrome.tabs.executeScript(tabId, data, (result:any[]) => {
        resolve(result)
      })
    })
  }
  public static chromeExecCommnad(command:"openFile"|"deleteDirectory"|"openDirectory"|"showFileInDirectory"|"executeBrowserAction"|"openDevTools"|"openProxySettings", param:any) {
    customChrome.task.execCommand(command, param)
  }
}

export interface IGetLicenseResult {
  clientId:string
  dongleId:string
  email:string
  serviceDate:Date
  username:string
  validDate:Date
}
